<?php

namespace App\Http\Controllers\User;

use App\Events\Message;
use App\Http\Controllers\BaseController;
use App\Models\UserSign;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class SignController extends BaseController
{
    public function config()
    {
        return $this->success([
             'sign_give_points' => admin_setting('sign_give_points'),
             'sign_give_rules' => admin_setting_array('sign_give_rules')
        ]);
    }


    public function view(Request $request)
    {

        $params = $this->validate($request,[
            'month' =>  'date_format:m'
        ]);
        $user_id =  auth('api')->id();
        $query = DB::table('user_signs')
            ->selectRaw("date_format(sign_time,'%Y-%m-%d') as date")
            ->where('user_id',$user_id);


        if (isset($params['month'])){
            $query->whereMonth('sign_time',$params['month']);
        }else{
            $query->whereMonth('sign_time',date('m'));
        }


        $signs = $query->get();

        if ($signs->isEmpty()){
            return  $this->success();
        }

        return $this->success(array_column($signs->toArray(),'date'));
    }


    public function index()
    {
        $user_id = auth('api')->id();
        $data = UserSign::query()
                        ->selectRaw('user_signs.*,(select count(friend_id) from user_follows where friend_id=user_signs.user_id and status=1 and user_id='.$user_id.') as is_follow')
                        ->with(['user:id,avatar,nickname,auth,user_title_id' => ['title:id,title']])->whereDate('sign_time',date('Y-m-d'))
                        ->simplePaginate(10);


        return $this->success($data);

    }


    public function show()
    {
        $user_id = auth('api')->id();
        $exist = DB::table('user_signs')
                    ->where('user_id',$user_id)
                    ->whereDate('sign_time',date('Y-m-d'))
                    ->exists();


        $continuous_sign_num = DB::table('users')->where('id',$user_id)->value('continuous_sign_num');

        $today_people_sign_num = DB::table('user_signs')
            ->whereDate('sign_time',date('Y-m-d'))
            ->count('id');

        $data = [
            'today_people_sign_num' => $today_people_sign_num,
            'continuous_sign_num' => $continuous_sign_num
        ];
        if($exist){
            $data['is_sign'] = true;
        }else{
            $data['is_sign'] = false;
        }

        return $this->success($data);
    }




    public function store()
    {
           $user_id = auth('api')->id();

           $today_exist = DB::table('user_signs')->where('user_id',$user_id)->whereDate('sign_time',date('Y-m-d'))->exists();

           if ($today_exist){
               return  $this->error('对不起您已经签到过了');
           }

           DB::table('user_tasks')
               ->insert([
                    'user_id' => $user_id,
                    'task_id' => 2,
                    'finish_time' => date('Y-m-d H:i:s')
               ]);

           $result = DB::table('user_signs')->insert([
                'user_id' => $user_id,
                'sign_time' => date('Y-m-d H:i:s')
           ]);

           $exist = DB::table('user_signs')->where('user_id',$user_id)->whereDate('sign_time',date('Y-m-d',strtotime('-1 days')))->exists();

           if ($exist){
               DB::table('users')->where('id',$user_id)->increment('continuous_sign_num');
           }else{
               DB::table('users')->where('id',$user_id)->update(['continuous_sign_num' => 1]);
           }

            $continuous_sign_num = DB::table('users')->where('id',$user_id)->value('continuous_sign_num');
            if ($continuous_sign_num==30){
                $this->finishTask($user_id,21,'完成签到连续30天任务');
            }

            if ($continuous_sign_num==90){
                $this->finishTask($user_id,22,'完成签到连续90天任务');
            }

           $sign_give_points = admin_setting('sign_give_points');
           if ($sign_give_points){
               DB::update('update users set points=points+'.$sign_give_points.',total_points=total_points+'.$sign_give_points.' where id='.$user_id);;
               DB::table('user_points_details')
                   ->insert([
                       'user_id' => $user_id,
                       'change_type' => 1,
                       'points' => $sign_give_points,
                       'remark' => '签到赠送',
                       'change_time' => date('Y-m-d H:i:s')
                   ]);

               event(new Message([
                   'user_id' => $user_id,
                   'type' => 4,
                   'content' =>'每日签到赠送积分已入账'
               ]));



               $sign_give_rules = admin_setting_array('sign_give_rules');

               if ($sign_give_rules){

                   foreach ($sign_give_rules as $rule){
                       if ($continuous_sign_num == $rule['sign_day']){
                           DB::update('update users set points=points+'.$rule['give_points'].',total_points=total_points+'.$rule['give_points'].' where id='.$user_id);
                           DB::table('user_points_details')
                               ->insert([
                                   'user_id' => $user_id,
                                   'change_type' => 1,
                                   'points' => $rule['give_points'],
                                   'remark' => '连续签到额外赠送',
                                   'change_time' => date('Y-m-d H:i:s')
                               ]);

                           event(new Message([
                               'user_id' => $user_id,
                               'type' => 4,
                               'content' =>'完成连续签到额外赠送积分已入账'
                           ]));
                       }
                   }
               }


//               DB::table('user_message')->insert([
//                   'user_id' => $user_id,
//                   'type' => 1,
//                   'content' =>  '恭喜您签到成功，为你赠送的'.$sign_give_index.'指数分已入账，请知晓！',
//                   'status' => 2,
//                   'message_type' => 1,
//                   'created_at' => date('Y-m-d H:i:s'),
//                   'updated_at' => date('Y-m-d H:i:s'),
//               ]);
           }

          return $result ? $this->success('签到成功') : $this->error('签到失败');
    }


    public function finishTask($user_id,$task_id,$remark)
    {

        $give_points = DB::table('tasks')->where('id',$task_id)->value('give_points');
        DB::table('user_tasks')
            ->insert([
                'user_id' => $user_id,
                'task_id' => $task_id,
                'finish_time' => date('Y-m-d H:i:s')
            ]);

        if ($give_points>0){
            DB::table('users')->where('id',$user_id)->increment('points',$give_points);
            DB::table('user_points_details')
                ->insert([
                    'user_id' => $user_id,
                    'change_type' => 1,
                    'points' => $give_points,
                    'remark' => $remark,
                    'change_time' => date('Y-m-d H:i:s')
                ]);
            event(new Message([
                'user_id' => $user_id,
                'type' => 4,
                'content' =>'完成签到任务赠送积分已入账'
            ]));
        }
    }
}
